﻿using Futil;
using OPCAutomation;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace OKDebug
{
    public partial class FrmOPC : Form
    {
        private OPCGroup _opcGroup;
        private OPCItem _opcItem;
        private OPCServer _opcServer = new OPCServer();
        private OPCBrowser _opcBrowser = null;

        public FrmOPC()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            Result result = new Result();
            string ip = txtIP.Text.Trim();
            string serverName = txtSeverName.Text.Trim();

            if (string.IsNullOrEmpty(ip))
            {
                MessageBox.Show("IP空！");
                txtIP.Focus();
                return;
            }

            if (string.IsNullOrEmpty(serverName))
            {
                MessageBox.Show("服务名空！");
                txtSeverName.Focus();
                return;
            }

            try
            {
                if ((OPCServerState)_opcServer.ServerState == OPCServerState.OPCDisconnected)
                {
                    _opcServer.Connect(serverName, ip);
                    if ((OPCServerState)_opcServer.ServerState == OPCServerState.OPCRunning)
                    {
                        _opcBrowser = _opcServer.CreateBrowser();
                        result.Success = true;
                        btnConnect.Text = "已连接OPC";
                        btnConnect.ForeColor = Color.White;
                        btnConnect.BackColor = Color.Green;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            string address = txtAddress.Text.Trim();
            if (string.IsNullOrEmpty(address))
            {
                MessageBox.Show("点位地址空！");
                return;
            }

            try
            {
                _opcServer.OPCGroups.RemoveAll();
                _opcGroup = _opcServer.OPCGroups.Add("NewGroup");
                _opcGroup.IsActive = true;
                _opcItem = _opcGroup.OPCItems.AddItem(address, 1);
                object value;
                object quality;
                object timestamp;
                _opcItem.Read(1, out value, out quality, out timestamp);
                txtValue.Text = value.ToString();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
